using FytSoa.Application.Crm.Param;
using FytSoa.Common.Enum;
using FytSoa.Common.Extensions;
using FytSoa.Domain.Crm;
using FytSoa.Sugar;
using FytSoa.Common.Utils;
using FytSoa.Common.Param;
using FytSoa.Common.Result;
using Mapster;
using Microsoft.AspNetCore.Mvc;

namespace FytSoa.Application.Crm;

/// <summary>
/// 客户信息服务接口
/// </summary>
[ApiExplorerSettings(GroupName = "v7")]
public class CrmCustomerService : IApplicationService 
{
    private readonly SugarRepository<CrmCustomer> _thisRepository;
    private readonly CrmOperateLogService _operateLogService;
    public CrmCustomerService(SugarRepository<CrmCustomer> thisRepository
    ,CrmOperateLogService operateLogService)
    {
        _thisRepository = thisRepository;
        _operateLogService = operateLogService;
    }
    
    /// <summary>
    /// 查询所有——分页
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<PageResult<CrmCustomerDto>> GetPagesAsync(PageParam param)
    {
        var queryQuery = _thisRepository.AsQueryable();
        if (!string.IsNullOrEmpty(param.Query))
        {
            var jsonParam=_thisRepository.Context.Utilities.JsonToConditionalModels(param.Query);
            queryQuery.Where(jsonParam);
        }
        var query = await queryQuery
            .WhereIF(!string.IsNullOrEmpty(param.Key),m=>m.Name.Contains(param.Key) || m.Tel.Contains(param.Key)
             || m.Tel.Contains(param.Key) || m.Email.Contains(param.Key))
            .WhereIF(param.Type!=-1,m=>m.Type==param.Type)
            .Includes(m=>m.EmployeeObj)
            .Includes(m=>m.SourceObj)
            .Includes(m=>m.LevelObj)
            .Includes(m=>m.IndustryObj)
            .OrderByDescending(m=>m.Id)
            .ToPageAsync(param.Page, param.Limit);
        return query.Adapt<PageResult<CrmCustomerDto>>();
    }

    /// <summary>
    /// 根据主键查询
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("{id}")]
    public async Task<CrmCustomerDto> GetAsync(long id)
    {
        var model = await _thisRepository.AsQueryable()
            .Includes(m=>m.EmployeeObj)
            .Includes(m=>m.SourceObj)
            .Includes(m=>m.LevelObj)
            .Includes(m=>m.IndustryObj)
            .FirstAsync(m=>m.Id==id);
        return model.Adapt<CrmCustomerDto>();
    }

    /// <summary>
    /// 添加
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    [UnitOfWork]
    public async Task AddAsync(CrmCustomerContact model)
    {
        var toDay = await _thisRepository.CountAsync(m=>m.CreateTime.ToString("yyyy-MM")==DateTime.Now.ToString("yyyy-MM"));
        model.Customer.Number = "C-".ResNumber(toDay, "yyyyMM");
        var isAny = await _thisRepository.IsAnyAsync(m => m.Name == model.Customer.Name);
        if (isAny)
        {
            throw new BusinessException("客户名称重复了");
        }
        var customerId = await _thisRepository.InsertReturnSnowflakeIdAsync(model.Customer.Adapt<CrmCustomer>());
        var contactRepository = _thisRepository.ChangeRepository<SugarRepository<CrmContact>>();
        var isContactAny = await contactRepository.IsAnyAsync(m => m.Name == model.Contact.Name && m.Mobile==model.Contact.Mobile);
        if (isContactAny)
        {
            throw new BusinessException("联系人重复了");
        }

        model.Contact.CustomerId = customerId;
        await contactRepository.InsertAsync(model.Contact.Adapt<CrmContact>());
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateId = customerId,
            Type = (int)OaOperateEnum.Customer,
            Remark = "创建了客户信息"
        });
    }

    /// <summary>
    /// 修改
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<bool> ModifyAsync(CrmCustomerAdd model)
    {
        var isAny = await _thisRepository.IsAnyAsync(m => m.Name == model.Name && m.Id!=model.Id);
        if (isAny)
        {
            throw new BusinessException("客户名称重复了");
        }
        //增加记录
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateId = model.Id,
            Type = (int)OaOperateEnum.Customer,
            Remark = "修改了客户信息"
        });
        return await _thisRepository.UpdateAsync(model.Adapt<CrmCustomer>());
    }
    
    /// <summary>
    /// 放入公海
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    public async Task ModifyJoinSeasAsync([FromBody]List<long> ids)
    {
        //增加记录
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateIds = ids,
            Type = (int)OaOperateEnum.Customer,
            Remark = "将客户放入公海"
        });
        await _thisRepository.UpdateAsync(m=>new CrmCustomer()
        {
            Type = 2,
            EmployeeId = 0
        },m=>ids.Contains(m.Id));
    }
    
    /// <summary>
    /// 转化为客户
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    public async Task ModifyJoinCustAsync([FromBody]List<long> ids)
    {
        //增加记录
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateIds = ids,
            Type = (int)OaOperateEnum.Customer,
            Remark = "将线索转化为客户"
        });
        await _thisRepository.UpdateAsync(m=>new CrmCustomer()
        {
            Type = 1,
        },m=>ids.Contains(m.Id));
    }
    
    /// <summary>
    /// 领取=移除公海
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    public async Task ModifyRemoveSeasAsync([FromBody]List<long> ids)
    {
        //增加记录
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateIds = ids,
            Type = (int)OaOperateEnum.Customer,
            Remark = "在公海领取了客户"
        });
        await _thisRepository.UpdateAsync(m=>new CrmCustomer()
        {
            Type = 1,
            EmployeeId = AppUtils.LoginId
        },m=>ids.Contains(m.Id));
    }
    
    /// <summary>
    /// 在公海中分配客户
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task ModifySeasAllotAsync(CrmCustomerAllot model)
    {
        //增加记录
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateIds = model.Ids,
            Type = (int)OaOperateEnum.Customer,
            Remark = "在公海分配了客户"
        });
        await _thisRepository.UpdateAsync(m=>new CrmCustomer()
        {
            Type = 1,
            EmployeeId = model.EmployeeId
        },m=>model.Ids.Contains(m.Id));
    }
    
    /// <summary>
    /// 加锁/解锁
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task ModifyLockAsync(CrmCustomerLock model)
    {
        //增加记录
        await _operateLogService.AddAsync(new CrmOperateLogDto()
        {
            OperateIds = model.Ids,
            Type = (int)OaOperateEnum.Customer,
            Remark = model.Lock ? "锁定了客户" :"解锁了客户"
        });
        await _thisRepository.UpdateAsync(m=>new CrmCustomer()
        {
            IsLock = model.Lock
        },m=>model.Ids.Contains(m.Id));
    }

    /// <summary>
    /// 删除,支持批量
    /// </summary>
    /// <param name="ids"></param>
    /// <returns></returns>
    [HttpDelete]
    public async Task<bool> DeleteAsync([FromBody]List<long> ids) =>
        await _thisRepository.DeleteAsync(m=>ids.Contains(m.Id));
}
